<template>
  <view>
    <view :class="{home:true, 'tripList_root':showModalView}">
      <view v-for="(item, index) in components" :key="index">
        <!-- 魔方组件 -->
        <cube-box v-if="item.value==='CubeBox'" id="CubeBox" :decoretionProperties="item.formData"></cube-box>
        <!-- 店铺导航组件 -->
        <shop-nav v-if="item.value==='StoreNavigation'" :navList="item.formData.storeNavigations"
          @AssembleReload="AssembleReload"></shop-nav>
        <!-- 优惠券组件 -->
        <coupon-component v-if="item.value==='Coupon'" :couponType="item.formData" :decoretionProperties="11111111"
          @stopRoll="stopRoll" ref="HomeCoupon"></coupon-component>
        <!-- 轮播图组件 -->
        <home-swiper v-if="item.value==='HomeSwiper' && item.formData.swiperList.length" id="HomeSwiper"
          :decoretionProperties="item.formData"></home-swiper>
        <!-- 分隔符组件 -->
        <separator v-if="item.value==='Separator'" id="Separator" :decoretionProperties="item.formData"></separator>
        <!-- 空白占位组件 -->
        <blank-paceholder v-if="item.value==='BlankPaceholder'" id="BlankPaceholder"
          :decoretionProperties="item.formData"></blank-paceholder>
        <!-- 图片组件 -->
        <imageCom v-if="item.value==='ImageCom'" id="ImageCom" :decoretionProperties="item.formData"></imageCom>
        <!-- 商品组件 -->
        <goods-ponents v-if="item.value==='Goods'" ref="GroupGoods" :decoretionProperties="item.formData">
        </goods-ponents>
        <!-- 搜索组件 -->
        <search-comp v-if="item.value==='Search'" id="SearchItem" :decoretionProperties="item.formData"
          @search="search"></search-comp>
        <!-- 标题组件 -->
        <title-bar v-if="item.value==='TitleBar'" id="TitleBar" :decoretionProperties="item.formData"></title-bar>
        <!-- 接龙组件 -->
        <chain v-if="item.value==='Chain'" id="Chain" :decoretionProperties="item.formData"></chain>
        <!-- 富文本组件 -->
        <Rich-text v-if="item.value==='RichText'" id="RichText" :decoretionProperties="item.formData"></Rich-text>
        <!-- 直播组件 -->
        <home-live v-if="item.value==='HomeLive'" id="HomeLive" :decoretionProperties="item.formData"></home-live>
        <!-- 商品轮播图 -->
        <goods-swiper v-if="item.value==='GoodSwiper'" id="GoodsSwiper" :decoretionProperties="item.formData">
        </goods-swiper>
        <!-- 视频组件 -->
        <video-com v-if="item.value==='VideoCom'" id="VideoCom" :decoretionProperties="item.formData"></video-com>
      </view>


      <!-- #ifdef MP-WEIXIN -->
      <official-account style="margin-top: 20px;"></official-account>
      <!-- #endif -->

      <!-- #ifndef MP-WEIXIN -->
      <view>当前为非微信小程序环境，不支持公众号关注组件，请自行调整当前弹窗内容！</view>
      <!-- #endif -->


      <auth :authType="authType" @authClick="authClick" state="home" @getLocation="getLocation"></auth>
      <shopManage :shopMsg="shopMsg" :shoptype="shoptype" :shopTime="shopTime" :shopStatus="shopStatus"
        style="z-index:1000000"></shopManage>
    </view>
    <home-coupon @stopRoll="stopRoll" id="HomeCoupon" :animation="animation" v-show="controlCoupon&& !isCustom">
    </home-coupon>
    <home-recycling catchtouchmove="true" id="HomeRecycling"></home-recycling>
  </view>
</template>

<script lang="ts">
  import {
    getAssembly
  } from "@/api/modules/decoration";
  import isEqual from "lodash/isEqual";
  // const app = getApp();
  import CubeBox from "./components/cube-box/cube-box.vue"
  import ShopNav from "./components/shop-nav/shop-nav.vue"
  import CouponComponent from "./components/coupon-component/coupon-component.vue"
  import HomeSwiper from "./components/home-swiper/home-swiper.vue"
  import separator from "./components/home-separator/home-separator.vue"
  import BlankPaceholder from "./components/blank-paceholder/blank-paceholder.vue"
  import imageCom from "./components/imageCom/imageCom.vue"
  import GoodsPonents from "./components/goods-ponents/goods-ponents.vue"
  import SearchComp from "./components/search-comp/search-comp.vue"
  import TitleBar from "./components/title-bar/title-bar.vue"
  import chain from "./components/chain/chain.vue"
  import RichText from "./components/rich-text/rich-text.vue"
  import HomeLive from "./components/home-live/home-live.vue"
  import GoodsSwiper from "./components/goods-swiper/goods-swiper.vue"
  import VideoCom from "./components/video-com/video-com.vue"
  import Auth from "@/components/auth/auth.vue"
  import shopManage from "@/components/shopManage/shopManage.vue"
  import HomeCoupon from "./components/home-coupon/home-coupon.vue"
  import HomeRecycling from "./components/home-recycling/home-recycling.vue"
    import {
    handUserid
  } from "@/api/modules/distribution";
  import {
    Component,
    Vue,
    Prop
  } from 'vue-property-decorator'

  @Component({
    components: {
      CubeBox,
      ShopNav,
      CouponComponent,
      HomeSwiper,
      separator,
      BlankPaceholder,
      imageCom,
      GoodsPonents,
      SearchComp,
      TitleBar,
      chain,
      RichText,
      HomeLive,
      GoodsSwiper,
      VideoCom,
      Auth,
      shopManage,
      HomeCoupon,
      HomeRecycling,
    }
  })
  export default class home extends Vue {
    name: string = "home"

    @Prop({
      type: Object
    })
    userInfo: Object;
    @Prop({
      type: Boolean,
      default: false
    })
    hasInCustom: Boolean
    @Prop({
      type: Boolean,
      default: false
    })
    isCustom: Boolean
    @Prop({
      type: Object
    })
    currentTab: Object
    @Prop({
      type: Number,
      default: 0
    })
    notSwitchTab: Number
    @Prop({
      type:String
    })
    userid: String


    authType: boolean = false
    showModalView: boolean = false
    components: Array < any > = []
    scrollTop: number = 0
    shoptype: boolean = false // 店铺禁用与打烊
    shopTime: string = "00:00" // 工作时间
    shopStatus: number = 2
    shopMsg: Object = {}
    controlCoupon: boolean = true

    // surpGood: any = {}
    GroupGoods: any
    HomeCoupon: any
    animation: any = {}

    get isCurrent() {
      return this.$store.state.settingStore.currentTab === this.name;
    }

    showview() {
      this.showModalView = true
    }

    closeview() {
      this.showModalView = false
    }

    // 组件周期函数--监听组件挂载完毕
    mounted() {
      this.getPageSetting();
      this.$Pubsub.on("app-launch", () => {
        this.getPageSetting();
      });
    }
    // 组件周期函数--实例创建完成
    created() {
      if(this.userid){
      handUserid(this.userid,{}).then(res=>{
             this.$emit("stopuserid", {}, {});
            uni.showToast({
            title: `你已成为${res}下级分销员`,
            icon: "none"
          });
            
          }).catch(err=>{
             this.$emit("stopuserid", {}, {});
             uni.showToast({
            title: `${err}`,
             icon: "none"
          });
          })
        }


         
      
      // this.surpGood = this.$refs.surpGood;
      this.GroupGoods = this.$refs.GroupGoods;
      this.HomeCoupon = this.$refs.HomeCoupon;
      this.getPageSetting();

      const obj = uni.getLaunchOptionsSync();
      const shopMsg = this.$store.state.shopset.shopInfo;
      this.$emit(
        "stopShow", {
          type: shopMsg.status !== 2 && obj.scene ? 0 : 1
        }
      );
      this.PageScroll({scrollTop:10})
    }


    /**
     * 用户登录授权
     */
    authClick() {
      this.authType = false
    }

    /**
     * 导航点击操作
     */
    navClick(itemLink) {
      this.reGetPageAssembly(itemLink.id);
      if (this.$store.state.settingStore.customName) {
        uni.setNavigationBarTitle({
          title: `${this.$store.state.settingStore.customName}`,
        });
        this.$store.state.commit("settingStore/setcustomName", "");
      }
    }

    PageScroll(e) {
      this.scrollTop = e.scrollTop
      const animation = uni.createAnimation({
        duration: 500,
        timingFunction: 'ease',
      })
      // const animation = this.animation
      animation.translate(50, 0).step();
      this.animation = animation.export();
      const timer = setTimeout(() => {
        if (this.scrollTop === e.scrollTop) {
          this.scrollTop = e.scrollTop;
          animation.translate(0, 0).step();
          this.animation = animation.export()
          clearTimeout(timer);
        }
      }, 500);
    }

    AssembleReload() {
      this.components = this.$store.state.settingStore.components
    }

    /** 获取页面组件 */
    async getPageAssembly() {
      try {
        if (!this.$store.state.settingStore.hasInCustom) {
          // 初始话通过聚合接口获取到首页数据
          this.components = this.$store.state.settingStore.components
        } else {
          // 除第一次外 进入首页需重新获取接口获取首页数据
          this.reGetPageAssembly(this.$store.state.settingStore.newCurrentPageId);
        }
        await this.getShopCom();
      } catch (error) {
        this.$Popup.toast(error);
      }
    }

    /** 获取页面组件 */
    async reGetPageAssembly(id: string | number = "") {
      try {
        const res = await getAssembly({
          pageId: id ? id : this.$store.state.settingStore.newCurrentPageId,
        });

        if (res && !isEqual(res, this.$storage.get(`reGetPageAssembly-${id}`))) {
          this.$storage.set(`reGetPageAssembly-${id}`, res, 3 * 24 * 60 * 60 * 1000);
        }

        const storageData = this.$storage.get(`reGetPageAssembly-${id}`);
        this.components = res ? this.parseAssembleList(storageData) : []
        // const page = this.store.settingStore.currentPageId

        await this.getShopCom();
      } catch (error) {
        this.$Popup.toast(error);
      }
    }

    /** 解析自定义页面组件数据 */
    parseAssembleList(assembleList) {
      const components = [];
      if (assembleList.length > 0) {
        assembleList.forEach(item => {
          const properties = JSON.parse(item.properties);
          components.push(properties);
        });
      }
      return components;
    }

    /**
     * 获取店铺状态
     */
    async getShopCom() {
      const shopMsg = this.$store.state.shopset.shopInfo;
      if (!shopMsg.businessHours) return;
      const time = JSON.parse(shopMsg.businessHours);
      if (shopMsg.status !== 2) {
        this.$store.commit('settingStore/setTabVisible', false);
        this.shopMsg = shopMsg
        this.shoptype = true
        this.shopTime = time[0].slice(0, 5)
        this.shopStatus = shopMsg.status
      } else {
        this.shoptype = false
      }
    }

    search(val) {
      this.GroupGoods = this.$refs.GroupGoods;
      if (this.GroupGoods && val.scope === 1) {
        this.GroupGoods.onSearch(val.name.detail);
      }
    }

    /** 向下调用 */
    resetInfo() {
      // if (this.ChoiceShop) {
      //   this.ChoiceShop.initSelect();
      // }
    }

    /** 获取页面组件 */
    async getPageSetting() {
      await this.getPageAssembly();
      this.animation = uni.createAnimation({});
    }

    changeControl() {
      this.controlCoupon = true
    }

    getLocation(e){
      this.authType = false
      this.stopRoll(e)
    }

    /**
     * 底部禁止滚动
     */
    stopRoll(e) {
      // debugger
      const type = e
      this.setData({
        showModalView: type
      })
      // this.showModalView = Boolean(e)
    }

    /**
     * 页面离开
     */
    async onDetached() {
      this.$store.commit('settingStore/setIftransFrom', false);
    }

    tohuishou() {
      uni.navigateTo({
        url: "/subcontract/pages/recycling/recycling",
      });
    }

  }
</script>

<style lang="scss" scoped>
  @include b(home) {
    background-color: #f8f8f8;
  }

  .icon {
    color: red;
  }

  .popupSty {
    width: 70%;
    height: 70%;
  }

  .tripList_root {
    top: 0px;
    left: 0px;
    width: 100%;
    height: 100%;
    overflow: hidden;
    position: fixed;
    z-index: 0;
  }

  .choiceShop2 {
    position: fixed;
    bottom: 300rpx;
    right: 40rpx;
    width: 90rpx;
    height: 90rpx;
    display: -webkit-box;
    display: flex;
    -webkit-box-align: center;
    align-items: center;
    -webkit-box-pack: center;
    justify-content: center;
    flex-wrap: wrap;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 100rpx;
    color: white;
    z-index: 10;

    .choiceWrap {
      width: 25px;
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
      align-content: center;
    }

    .ft {
      font-size: 10px;
      margin-top: -6rpx;
    }
  }
</style>